var express = require('express');
var router = express.Router();

var user = {};
/* GET home page. */
router.get('/', function(req, res, next) {
  console.log(req.session.user);
  res.render('index', { title: '聊天室', user: req.session.user });
});

router.get('/login', function(req, res, next) {
  res.render('login', {alertMessage: null});
});

router.get('/signup', function(req, res, next) {
  res.render('signup', {alertMessage: null});
});

router.post('/login', function(req, res, next) {
  let {username, psd} = req.body;
  if (!user[username]) {
    res.render('login', {alertMessage: "The user doesn't exist!"});
    return;
  } 
  if (user[username].psd !== psd) {
    res.render('login', {alertMessage: "The password isn't correct!"});
    return;
  }
  req.session.user = username;
  console.log(req.session.user);
  res.redirect('/');
});

router.post('/signup', function(req, res, next) {
  let {username, psd, confirm} = req.body;
  if (user.username) {
    res.render('signup', {alertMessage: "The username exists, try another one"});
    return;
  }
  if (psd !== confirm) {
    res.render('signup', {alertMessage: "The password doesn't match, try again"});
    return;
  }

  user[username] = {
    username: username,
    psd: psd
  };
  console.log(user);
  res.render('login', {alertMessage: null});
});

router.get('logout', function(req, res) {
  res.locals.user = req.session.user = null;
  res.redirect('/');
});

module.exports = router;
